/**
 * 商品分类模块
 */
const fs = require('fs');
const { getUniqueId } = require("../utils/time");
const { isRequire } = require('../utils/common');
const { paginateArray, PAGE_SIZE } = require('../utils/page');

// 商品分类对象
const productType = {
    id: '',
    productTypeName: '',
    value: '',
    createTime: '',
    remark: '' //描述
}

// 商品分类数据文件地址
const filePath = './data/productType.txt';

// 商品对象必填字段
const requireKeys = {
    "productTypeName": "商品类型名称",  
    "value": "商品类型值", 
    "createTime": "创建时间",
    "remark": "商品类型描述",
}

/**
 * 查询所有商品分类并返回
 * @returns 
 */
async function readProductType() {
    try {
        const res = await fs.readFileSync(filePath, 'utf-8');
        const data = res.toString();
        // 判断是否有数据
        if (data) {
            const arr = JSON.parse(data);
            return Promise.resolve(arr);
        } else {
            return Promise.resolve([]);
        }
    } catch (error) {
        // 判断是否文件不存在
        if (String(error).indexOf('no such file or directory') !== -1) {
            return Promise.resolve([]);
        }
        return Promise.reject(error);
    }
}

/**
 * 添加商品分类
 * @param {*} content 商品分类信息
 * @returns 
 */
async function addProductType(content) {
    try {
        const res = await readProductType();
        // 判断商品类别名称是否重复
        const index = res.findIndex((item) => item.productTypeName === content.productTypeName);
        if (index > -1) {
            return Promise.reject('该商品类别名称已存在');
        }
        const uniqueId = getUniqueId();
        content.id = uniqueId;
        // 当前时间戳
        const timestamp = Math.floor(Date.now() / 1000);
        content.createTime = timestamp;
        // 商品分类value值自增
        content.value = String(res.length + 1);
        // 遍历判断是否必填
        let flag = isRequire(requireKeys, content);
        if(!flag){
            return Promise.reject('必填项不完整');
        }
        if (res && Array.isArray(res)) {
            res.unshift(content);
        }
        const data = JSON.stringify(res)
        await fs.writeFileSync(filePath, data);
        return Promise.resolve();
    } catch (error) {
        console.log(error);
        return Promise.reject();
    }
}

/**
 * 删除商品类别
 * @param {*} id 商品类别id
 * @returns 
 */
async function deleteProductType(query) {
    try {
        const res = await readProductType();
        const index = res.findIndex((item) => query.id === item.id);
        res.splice(index, 1);
        const data = JSON.stringify(res)
        await fs.writeFileSync(filePath, data);
        return Promise.resolve();
    } catch (error) {
        return Promise.reject();
    }
}

/**
 * 编辑商品分类
 * @param {*} content 商品分类信息
 * @returns 
 */
async function updateProductType(content) {
    try {
        const res = await readProductType();
        console.log(-1);
        // 遍历判断是否必填
        let flag = isRequire(requireKeys, content);
        if(!flag){
            return Promise.reject('必填项不完整');
        }
        const id = content.id;
        let index = -1;
        if (res && Array.isArray(res)) {
           index = res.findIndex((item) => item.id === id);
        }
        if(index < 0){
            throw new Error();
        }
        console.log(0);
        const data = JSON.parse(JSON.stringify(res));
        // 修改商品分类信息
        data.splice(index, 1);
        data.unshift(content);
        const rs = await fs.writeFileSync(filePath, JSON.stringify(data));
        console.log(rs);
        return Promise.resolve();
    } catch (error) {
        console.log(error);
        return Promise.reject();
    }
}

/**
 * 分页查询商品分类
 * @returns 
 */
async function queryProductType(params) {
    const { pageNum, searchParams } = params;
    try {
        const res = await fs.readFileSync(filePath, 'utf-8');
        const data = res.toString();
        // 判断是否有数据
        if (data) {
            const arr = JSON.parse(data);
            const pageResult = paginateArray(arr, pageNum, PAGE_SIZE, searchParams)
            console.log(pageResult);
            return Promise.resolve(pageResult);
        } else {
            return Promise.resolve([]);
        }
    } catch (error) {
        // 判断是否文件不存在
        if (String(error).indexOf('no such file or directory') !== -1) {
            return Promise.resolve([]);
        }
        return Promise.reject(error);
    }
}

module.exports = { 
    productType, 
    readProductType,
    addProductType,
    deleteProductType,
    updateProductType,
    queryProductType,
}